package com.drinks.yiniang.ui.activity.common;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import com.drinks.yiniang.R;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.hansen.library.utils.FileProviderUtils;
import com.drinks.yiniang.utils.RegularUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.drinks.yiniang.utils.ZXingUtils;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.pickerimage.PickImageHelper;
import com.hansen.library.pickerimage.model.PhotoInfo;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;
import com.hansen.zxinglibrary.scanner.CaptureManager;
import com.hansen.zxinglibrary.scanner.DecoratedBarcodeView;
import com.hansen.zxinglibrary.zxing.integration.android.IntentIntegrator;
import com.hansen.zxinglibrary.zxing.integration.android.IntentResult;

import java.io.File;
import java.util.List;

import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FILE_PATH;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FROM_LOCAL;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_PHOTO_LISTS;

/**
 * 扫码页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class YNCaptureActivity extends BaseTranBarActivity implements OnNavgationBarClickListener {

    private final int REQ_CHOOSE_PIC_CODE = 0x01;

    //nav
    private NavigationBarLayout nav_bar_capture;
    private DecoratedBarcodeView zxing_barcode_scanner;

    private CaptureManager mCapture;

    private PickImageHelper.PickImageOption pickImgOption;

    @Override
    protected void initView() {
        nav_bar_capture = findViewById(R.id.nav_bar_capture);

        zxing_barcode_scanner = findViewById(R.id.zxing_barcode_scanner);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mCapture = new CaptureManager(this, zxing_barcode_scanner);
        mCapture.initializeFromIntent(getIntent(), savedInstanceState);
        mCapture.setResultCallBack(new CaptureManager.ResultCallBack() {
            @Override
            public void callBack(int requestCode, int resultCode, Intent data) {
                IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

                toGoodsDetail(result.getContents());
            }
        });

        mCapture.decode();
    }

    @TargetApi(Build.VERSION_CODES.M)
    protected void setStatusBarColor() {

    }

    @Override
    protected void initListener() {
        nav_bar_capture.setOnNavgationBarClickListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_yncapture;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        initPickerImage();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCapture.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCapture.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCapture.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mCapture.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return zxing_barcode_scanner.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQ_CHOOSE_PIC_CODE://选择图片回调
                    String filePath = data.getStringExtra(EXTRA_FILE_PATH);

                    if (!data.getBooleanExtra(EXTRA_FROM_LOCAL, false)) {
                        filePath = data.getStringExtra(EXTRA_FILE_PATH);
                    } else {
                        List<PhotoInfo> imageList = (List<PhotoInfo>) data.getSerializableExtra(EXTRA_PHOTO_LISTS);

                        if (!CommonUtils.isEmptyList(imageList)) {
                            filePath = imageList.get(0).getAbsolutePath();
                        }
                    }

                    if(StringUtils.isEmpty(filePath)) {
                        ToastUtils.showShort("选择图片失败!");
                        return;
                    }

                    File file = new File(filePath);

                    if (file == null) {
                        ToastUtils.showShort("选择图片失败!");
                        return;
                    }

                    ImageScanningTask scanningTask = new ImageScanningTask(FileProviderUtils.uriFromFile(mContext, file),
                            new ImageScanningCallback() {
                                @Override
                                public void onFinishScanning(String result) {
                                    toGoodsDetail(result);
                                }
                            });

                    scanningTask.execute();
                    break;
                default:
                    break;
            }
        }
    }

    private void toGoodsDetail(String result) {
        if(result == null) {
            ToastUtils.showShort("Cancelled");
        }

        LogUtils.e(result);

        String goodsId = RegularUtils.getGoodsQrCodeScanResult(result);

        if(!StringUtils.isEmpty(goodsId)) {
            Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
            intent.putExtra(Constants.KeyGoodsId, goodsId);
            startActivity(intent);

            finish();
        } else {// 识别失败
            ToastUtils.showShort(R.string.text_only_recognition_goods_qr_code);
            mCapture.onResume();
        }
    }

    //选择图片
    private void initPickerImage() {
        if (pickImgOption == null) {
            pickImgOption = new PickImageHelper.PickImageOption();
            pickImgOption.multiSelect = false;
        }

        PickImageHelper.pickImageFromAlbum(mContext, REQ_CHOOSE_PIC_CODE, pickImgOption);
    }

    public class ImageScanningTask extends AsyncTask<Uri, Void, String> {
        private Uri uri;
        private ImageScanningCallback callback;

        public ImageScanningTask(Uri uri, ImageScanningCallback callback) {
            this.uri = uri;
            this.callback = callback;
        }

        @Override
        protected String doInBackground(Uri... params) {
            return ZXingUtils.scanImage(uri);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            callback.onFinishScanning(result);
        }
    }

    public interface ImageScanningCallback {
        void onFinishScanning(String result);
    }
}
